package com.keya.features.gateway;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.keya.base.WorkSpace;
import com.keya.device.GatewayProperties;
import com.keya.dicomtask.DcmInfoBO;
import com.keya.dicomtask.DicomTask;
import com.keya.dicomtask.DicomTaskService;
import com.keya.dicomtask.VersionGenerator;
import com.keya.mapper.DicomTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@Order(1)
public class StudyTransferManager implements ApplicationRunner {

    @Resource
    private Gateway gateWay;
    @Resource
    private GatewayProperties gatewayProperties;

    String GROUP_SPLIT = "@@##@@";

    Map<String, Date> studyTrace = new ConcurrentHashMap<>();

    private final Map<String, Map<String, SeriesGroup>> records = new ConcurrentHashMap<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        WorkSpace workSpace = new WorkSpace(gatewayProperties.getStorage());
        workSpace.prepare();
        try {
            String aeTitle = gatewayProperties.getAetitle();
            gateWay.setAETitle(aeTitle);
            gateWay.run();
        } catch (Exception e) {
            log.error("Gateway start failed: ", e);
            throw new RuntimeException(e);
        }
        log.info("gateway started");
    }

    public void onNewDicom(String aetitle, String StudyInstanceUID,
                           String AccessionNumber, String SeriesInstanceUID,
                           String SOPInstanceUID) {
        synchronized (this) {
            String k = String.format("%s" + GROUP_SPLIT + "%s", aetitle, StudyInstanceUID);
            studyTrace.put(k, new Date());
            Map<String, SeriesGroup> seriesGroupMap = records.get(k);
            if (seriesGroupMap != null) {
                SeriesGroup seriesGroup = seriesGroupMap.get(SeriesInstanceUID);
                if (seriesGroup != null) {
                    StudyRecord studyRecord = seriesGroup.getStudyRecord();
                    studyRecord.setUpdatedAt(new Date());
                    studyRecord.setCount(studyRecord.getCount() + 1);
                } else {
                    seriesGroup = new SeriesGroup();
                    StudyRecord studyRecord = new StudyRecord(null, aetitle, StudyInstanceUID, AccessionNumber, 1, new Date(), new Date());
                    seriesGroup.setStudyRecord(studyRecord);
                    seriesGroup.setSeriesInstanceUID(SeriesInstanceUID);
                    seriesGroupMap.put(SeriesInstanceUID, seriesGroup);
                }
            } else {
                seriesGroupMap = new HashMap<>();
                SeriesGroup seriesGroup = new SeriesGroup();
                StudyRecord studyRecord = new StudyRecord(null, aetitle, StudyInstanceUID, AccessionNumber, 1, new Date(), new Date());
                seriesGroup.setStudyRecord(studyRecord);
                seriesGroup.setSeriesInstanceUID(SeriesInstanceUID);
                seriesGroupMap.put(SeriesInstanceUID, seriesGroup);
                records.put(k, seriesGroupMap);
            }
        }
    }

    @Resource
    DicomTaskService dicomTaskService;
    @Resource
    VersionGenerator versionGenerator;

    public void testTick() {
        Date now = new Date();
        for (Map.Entry<String, Map<String, SeriesGroup>> entry : records.entrySet()) {
            String aeTitle = entry.getKey().split(GROUP_SPLIT)[0];
            String StudyInstanceUID = entry.getKey().split(GROUP_SPLIT)[1];
            Date date = studyTrace.get(entry.getKey());
            SeriesGroup seriesGroup = (SeriesGroup) entry.getValue().values().toArray()[0];
            String AccessionNumber = seriesGroup.getStudyRecord().getAccessionNumber();
            long passed = now.getTime() - date.getTime();
            if (passed >= gatewayProperties.getTimeOut()) {
                log.info(String.format("StudyId接收完成 ID：%s", StudyInstanceUID));
                DcmInfoBO dcmInfoBO = new DcmInfoBO()
                        .setAetitle(aeTitle)
                        .setAccessionNumber(AccessionNumber)
                        .setStudyInstanceUID(StudyInstanceUID);
                dicomTaskService.save(dcmInfoBO);
                records.remove(entry.getKey());
            }
        }
    }


}
